import {Component, Input, OnInit, ViewChild} from '@angular/core';
import {DocumentService} from '../shared/document.service';
import {CollectionViewer, DataSource} from '@angular/cdk/collections';
import {BehaviorSubject, Observable} from 'rxjs';
import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material';
import {ActivatedRoute, Router} from '@angular/router';

@Component({
  selector: 'app-document-list',
  templateUrl: './document-list.component.html',
  styleUrls: ['./document-list.component.css'],
  providers: [DocumentService]
})
export class DocumentListComponent implements OnInit {
  displayedColumns = ['selector', 'id', 'title', 'spider', 'oper'];
  // exampleDatabase = new ExampleDatabase();
  // dataSource: ExampleDataSource ;
  dataSource: MatTableDataSource<Document>;
  documents: Document[] = [];
  selectedValue: string;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(private documentService: DocumentService, private router: Router) { }

  ngOnInit() {
    // alert('aaa');
    // this.dataSource = new ExampleDataSource(this.exampleDatabase);
    this.documentService.getDocumentList().subscribe( (value) => {
      this.documents = <Document[]><any>value;
      this.dataSource = new MatTableDataSource<Document>(this.documents);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
      // this.dataSource = new DocumentDataSource(this.documents, this.paginator, this.sort);
      // this.dataSource.paginator = this.paginator;
      // if (documents) {
      //
      // }
    });
  }
  selectRow(row) {
    alert(row.id);
    this.documentService.currentDocument = row;
    this.router.navigate(['documents/', row.id]);
  }
  onDelClicked(event) {
    alert(event);
  }
  onAssignClicked(event) {
    alert(event);
  }
  applyFilter(filterValue: string) {
    filterValue = filterValue.trim();
    filterValue = filterValue.toLowerCase();
    this.dataSource.filterPredicate = (data: Document, filter: string) => data.title.indexOf(filterValue) !== -1;
    this.dataSource.filter = filterValue;
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }
}

/**
 * Data source to provide what data should be rendered in the table. Note that the data source
 * can retrieve its data in any way. In this case, the data source is provided a reference
 * to a common data base, ExampleDatabase. It is not the data source's responsibility to manage
 * the underlying data. Instead, it only needs to take the data and send the table exactly what
 * should be rendered.
 */
export class DocumentDataSource extends DataSource<Document> {

  constructor(private documents: Document[], private paginator: MatPaginator, private sort: MatSort) {
    super();
  }
  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(collectionViewer: CollectionViewer): Observable<Document[]> {
    return new BehaviorSubject<Document[]>(this.documents);
    // return Observable.merge(...displayDataChanges).map(() => {
    //   // const data = this._exampleDatabase.data.slice();
    //   const data = this.getSortedData();
    //   // Grab the page's slice of data.
    //   const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
    //   return data.splice(startIndex, this._paginator.pageSize);
    // });
  }

  disconnect(collectionViewer: CollectionViewer): void {
  }
}

//////
export interface UserData {
  id: number;
  name: string;
  progress: string;
}
export class ExampleDatabase {
  /** Stream that emits whenever the data has been modified. */
  dataChange: BehaviorSubject<UserData[]> = new BehaviorSubject<UserData[]>([]);
  get data(): UserData[] { return this.dataChange.value; }

  constructor() {
    // Fill up the database with 100 users.
    for (let i = 0; i < 100; i++) { this.addUser(); }
  }

  /** Adds a new user to the database. */
  addUser() {
    const copiedData = this.data.slice();
    copiedData.push(this.createNewUser());
    this.dataChange.next(copiedData);
  }

  /** Builds and returns a new User. */
  private createNewUser() {

    return {
      id: 1,
      name: 'example',
      progress: Math.round(Math.random() * 100).toString()
    };
  }
}
export class ExampleDataSource extends DataSource<any> {
  constructor(private _exampleDatabase: ExampleDatabase) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<UserData[]> {
    return this._exampleDatabase.dataChange;
  }

  disconnect() { }
}
